using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Permissions;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Handler.Users.Permissions
{
    /// <summary>
    /// 创建权限处理器
    /// </summary>
    public class CreatePermissionHandler : IRequestHandler<CreatePermissionCommand, APIResult<PermissionDTO>>
    {
        private readonly IRepository<Permissionmodel> permissionRepository;

        public CreatePermissionHandler(IRepository<Permissionmodel> permissionRepository)
        {
            this.permissionRepository = permissionRepository;
        }

        public async Task<APIResult<PermissionDTO>> Handle(CreatePermissionCommand request, CancellationToken cancellationToken)
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(request.PermissionCode) ||
                string.IsNullOrWhiteSpace(request.PermissionName))
            {
                return APIResult<PermissionDTO>.Faile("权限编号和名称不能为空");
            }

            var code = request.PermissionCode.Trim();
            var name = request.PermissionName.Trim();

            // 检查权限编号是否已存在
            bool codeExists = await permissionRepository.GetAll()
                .Where(p => p.IsDel == false && p.PermissionCode == code)
                .AnyAsync();

            if (codeExists)
            {
                return APIResult<PermissionDTO>.Faile("权限编号已存在");
            }

            // 检查父级权限是否存在
            if (request.ParentId > 0)
            {
                var parentPermission = await permissionRepository.GetByIdAsync(request.ParentId);
                if (parentPermission == null || parentPermission.IsDel)
                {
                    return APIResult<PermissionDTO>.Faile("父级权限不存在");
                }
            }

            // 创建权限
            var permission = new Permissionmodel
            {
                Id = YitIdHelper.NextId(),
                PermissionCode = code,
                PermissionName = name,
                PermissionUrl = request.PermissionUrl,
                ParentId = request.ParentId,
                PermissionType = request.PermissionType,
                Icon = request.Icon,
                Sort = request.Sort,
                Status = 1, // 默认启用
                Description = request.Description,
                Remark = request.Remark,
                //Createdate = DateTime.Now,
                //Createname = "系统管理员", // TODO: 从当前登录用户获取
                IsDel = false
            };

            int rows = await permissionRepository.AddAsync(permission);
            if (rows <= 0)
            {
                return APIResult<PermissionDTO>.Faile("创建权限失败");
            }

            // 构造返回DTO
            var dto = new PermissionDTO
            {
                Id = permission.Id,
                PermissionCode = permission.PermissionCode,
                PermissionName = permission.PermissionName,
                PermissionUrl = permission.PermissionUrl,
                ParentId = permission.ParentId,
                PermissionType = permission.PermissionType,
                Icon = permission.Icon,
                Sort = permission.Sort,
                Status = permission.Status,
                Description = permission.Description,
                Remark = permission.Remark
            };

            return APIResult<PermissionDTO>.Ok("创建权限成功", dto);
        }
    }
}
